﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class YYPPGrey : PostEffectBase {


    Camera tempCamera;
  

    private Hashtable hashCameras = new Hashtable();

    public LayerMask tempCameraLayers = -1;


    Camera curCamera;
    private void Awake()
    {
        curCamera = GetComponent<Camera>();
    }


    private void OnDisable()
    {
        foreach (DictionaryEntry kvp in hashCameras)
        {
            var cc = (Camera)kvp.Value;
            if (cc != null)
            {
                GameObject go = ((Camera)kvp.Value).gameObject;
                if (go != null)
                    DestroyImmediate(go);
            }
        }
        hashCameras.Clear();
        //if (curCamera != null)
        //    curCamera.cullingMask |= tempCameraLayers.value;
    }

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        //Camera cam = Camera.current;
        CreateCamera(curCamera);
        UpdateCamera();

        Graphics.Blit(source, destination, _Material);
    }

    private void UpdateCamera()
    {
        tempCamera.cullingMask = tempCameraLayers.value;
        //Camera.current.cullingMask &= ~(tempCameraLayers.value);
    }


    private void CreateCamera(Camera currentCamera)
    {
        tempCamera = null;
        tempCamera = hashCameras[currentCamera] as Camera;
             

        if (tempCamera == null)
        {
            GameObject go = new GameObject("Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));
            tempCamera = go.GetComponent<Camera>();
            tempCamera.CopyFrom(currentCamera);

            tempCamera.depth = currentCamera.depth + 1;
            tempCamera.clearFlags = CameraClearFlags.Nothing;
            //cameras[curCamera.GetInstanceID()] = tempCamera;

            hashCameras[currentCamera] = tempCamera;
        }
        
    }

}
